//
//  GoodsListCollectionViewController.m
//  FreightAssistant
//
//  Created by leo on 15/10/27.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "CommodityListTableViewController.h"

#import "CommodityEditViewController.h"


@interface CommodityListTableViewController () {
    
    KKSearchBar *_kk_searchBar;
    KKCommodityItemList *_commodityItemList;
    NSMutableArray *_selectedGoodsItemArray;
}

@end

@implementation CommodityListTableViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"货品";
    
    _kk_searchBar = [[KKSearchBar alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), 40)];
    _kk_searchBar.placeholder = @"搜索";
    self.tableView.tableHeaderView = _kk_searchBar;
    self.tableView.tableFooterView = [UIView new];
    
    _commodityItemList = [KKCommodityItemList new];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    if (_type == CommodityListViewControllerTypeIsCheck) {
        
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemAdd target: self action: @selector(actionOfAdd:)];
        rightItem.tintColor = [UIColor whiteColor];
        
        self.navigationItem.rightBarButtonItem = rightItem;
        
        self.showMainItem = true;        
    }
    else {
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemSave target: self action: @selector(actionOfSave:)];
        rightItem.tintColor = [UIColor whiteColor];
        
        self.navigationItem.rightBarButtonItem = rightItem;
        
        _selectedGoodsItemArray = [NSMutableArray array];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear: animated];
    
    [self downloadItemsFromDBWithSearchText: nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods

- (void)downloadItemsFromDBWithSearchText:(NSString*)searchText {
    
    __weak KKCommodityItemList *weakItemList = _commodityItemList;
    __weak UITableView *weakTableView = self.tableView;
    
    if (_type == CommodityListViewControllerTypeIsCheck || _type == CommodityListViewControllerTypeIsSupplyOrder) {
        
        [KKDataBaseAPIInterface searchCommodityItemsWithSearchText: searchText withEnabled: true successful:^(id object) {
            [weakItemList appendItemsWithArray: object];
            [weakTableView reloadData];
        } faile: nil];
    }
    else {
        
        [KKDataBaseAPIInterface searchCommodityItemsWithSearchText: searchText withEnabled: false successful:^(id object) {
            [weakItemList appendItemsWithArray: object];
            [weakTableView reloadData];
        } faile: nil];
    }
}

- (void)deleteItemFromDBWithIndexPath:(NSIndexPath*)indexPath {
    
    KKCommodityItem *item = [_commodityItemList objectAtIndex: indexPath.row];
    
    __weak typeof(_commodityItemList) weakItemList = _commodityItemList;
    __weak UITableView *weakTableView = self.tableView;
    
    [KKDataBaseAPIInterface deleteCommodityItemWithIdentifier: item.kk_identifier successful:^(id object) {
        [weakItemList removeObjectOfIndex: indexPath.row];
        [weakTableView deleteRowsAtIndexPaths: @[indexPath] withRowAnimation: UITableViewRowAnimationAutomatic];
    } faile: nil];
}

#pragma mark - Action methods

- (void)actionOfAdd:(UIBarButtonItem*)item {
    
    CommodityEditViewController *editViewController = [CommodityEditViewController viewControllerFromStoryboard];
    [self.navigationController pushViewController: editViewController animated: true];
}

- (void)actionOfSave:(UIBarButtonItem*)item {
    
    if (self.editResultBlock) {
        self.editResultBlock(_selectedGoodsItemArray);
    }
    [self.navigationController popViewControllerAnimated: true];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _commodityItemList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommodityItemTableViewCell *cell = [CommodityItemTableViewCell cellFromTableView: tableView];
    
    if (self.type != CommodityListViewControllerTypeIsCheck) {
        
        UIView *contentView = [cell contentView];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(CGRectGetWidth(contentView.bounds) - 18, (CGRectGetHeight(contentView.bounds) - 14)/2, 14, 14)];
        imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
        imageView.tag = NSIntegerMax;
        imageView.image = [UIImage imageNamed:@"icon_check_item_normal"];
        [contentView addSubview: imageView];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    KKCommodityItem *item = [_commodityItemList objectAtIndex: indexPath.row];
    

    cell.kk_itemNameLabel.text = item.kk_name;
    cell.kk_itemPurchasePriceLabel.text = [NSString stringWithFormat: @"进价:¥%.2f", [item.kk_purchasePrice doubleValue]];
    cell.kk_itemPriceLabel.text = [NSString stringWithFormat: @"售价:¥%.2f", [item.kk_price doubleValue]];
    cell.kk_itemInventoryLabel.text = [NSString stringWithFormat: @"库存:%@", item.kk_inventory];
    
    UIImageView *imageView = (UIImageView*)[[cell contentView] viewWithTag: NSIntegerMax];
    BOOL hasSelected = [_selectedGoodsItemArray containsObject: item];
    imageView.image = [UIImage imageNamed: hasSelected ? @"icon_check_item_selected" : @"icon_check_item_normal"];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    KKCommodityItem *item = [_commodityItemList objectAtIndex: indexPath.row];
    
    if (self.type == CommodityListViewControllerTypeIsCheck) {
        
        //  编辑修改
        CommodityEditViewController *editViewController = [CommodityEditViewController viewControllerFromStoryboard];
        editViewController.kk_commodityItem = item;
        [self.navigationController pushViewController: editViewController animated: true];
    }
    else {
        
        if ([_selectedGoodsItemArray containsObject: item]) {
            [_selectedGoodsItemArray removeObject: item];
        }
        else {
            [_selectedGoodsItemArray addObject: item];
        }
        
        [tableView reloadRowsAtIndexPaths: @[indexPath] withRowAnimation: UITableViewRowAnimationFade];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.viewcontrollerType == KKViewControllerTypeChoose ? false : true;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        __weak typeof(self) weakSelf = self;
        [[KKAlertView shareInterce] showWithTitle: @"提示" andWithMessage: @"确定要删除这件货品的信息嘛?" andWithCancelTitle: @"取消" andWithCancelHandle: nil andWithSureTitle: @"确定" andWithSureHandle:^{
            
            [weakSelf deleteItemFromDBWithIndexPath: indexPath];
        }];
    }
}

@end
